﻿import os
import time

from appium.webdriver.connectiontype import ConnectionType
from appium import webdriver

from config.constants import Constants


def isNetworkConnected(devices_name, host):
    """
    判断网络是否连接正常
    :param devices_name: 设备名称 adb devices 可以获取（可通过device_util::isDevicesConnected获取）
    :param host: 需要ping的域名
    :return:网络是否连接正常
    """
    if devices_name is Constants.EMPTY_RESULT or devices_name is None:
        print("判断网络是否连接正常失败：传入的设备名称为空！")
        return False
    shell = 'adb -s %s shell ping -c 1 %s' % (devices_name, host)
    # 获取结果
    result = os.popen(shell)
    for line in result.readlines():
        if 'ms' in line:
            # PING gtm-cn-09k1ypboo0n.fipinfo.dfitc.com.cn (59.46.226.101) 56(84) bytes of data.
            # 64 bytes from 59.46.226.101: icmp_seq=1 ttl=55 time=21.7 ms
            print("当前设备网络连接正常：%s" % line)
            return True
    #  ping: unknown host fip.dfitc.com.cn
    print("当前设备网络未连接！")
    return False


def reconnectedNetwork(driver: webdriver):
    """
    网络重连
    :param driver:已连接的设备
    :return:
    """
    if driver is not None:
        print(f'当前设备网络连接状态： {driver.network_connection}')
        print("关闭设备网络连接...")
        driver.set_network_connection(ConnectionType.NO_CONNECTION)
        time.sleep(Constants.TURN_ON_NETWORK_INTERNAL)
        print("重启设备网络连接...")
        driver.set_network_connection(ConnectionType.ALL_NETWORK_ON)
        time.sleep(Constants.TURN_OFF_NETWORK_INTERNAL)
        print("重启设备网络接完成！")
        return True
    else:
        print("重启设备网络失败，driver is None！")
        return False


def checkNetworkAndReconnect(driver: webdriver, devices_name: str, host: str,
                             need_retry_connect=True, retry_connect_count=Constants.MAX_NUM_OF_NETWORK_RECONNECTION):
    """
    检查网络连接状态，若网络未连接则重连
    :param driver:
    :param devices_name:
    :param host:
    :param need_retry_connect:重启后连接失败需要重试-默认重试
    :param retry_connect_count:重试次数-默认为 Constants.MAX_NUM_OF_NETWORK_RECONNECTION
    :return:
    """
    # 重置重连次数 不重连时默认为1
    if retry_connect_count <= 0:
        retry_connect_count = Constants.MAX_NUM_OF_NETWORK_RECONNECTION
    if not need_retry_connect:
        retry_connect_count = 1

    network_connected = False
    while retry_connect_count > 0:
        if not isNetworkConnected(devices_name, host):
            reconnectedNetwork(driver)
        else:
            network_connected = True
            break
        retry_connect_count -= 1
    # 网络连接正常
    if network_connected:
        return True
    # 重连后再次检测网络连接状态
    if not isNetworkConnected(devices_name, host):
        print("当前设备网络未连接！")
        return False
    return True
